<!-- 表格组件 -->
<script lang="tsx" setup>
import { toRaw } from "vue";

import type { TableColumnOption } from "@/components/table-widget/table-widget.vue";
import TableWidget from "@/components/table-widget/table-widget.vue";
import {
	CHECK_PLAN_TYPE_OPTIONS,
	getEnumOptionsField,
} from "@/config/enum-options";
import { whManagerBsTbCheckPlanDeleteByIdIdUsingPost } from "@/genapi/wh";

import { injectState } from "../state";

defineOptions({ name: "Sheet" });

const {
	selectedList,
	tableRef,
	detailDialogRef,
	page: { records, isLoading, execute },
} = injectState()!;

watch(records, () => tableRef.value?.table?.clearSelection());

const onDelete = async (row: (typeof records.value)[0]) => {
	await ElMessageBox.confirm(
		`您即将删除【${row.name ?? "未知"}】，删除后不可恢复，是否确认删除？`,
		{
			type: "error",
			title: "提示",
		},
	);
	await whManagerBsTbCheckPlanDeleteByIdIdUsingPost({ path: { id: row.id! } });
	ElMessage.success("删除成功");
	await execute();
};

const columns: TableColumnOption<(typeof records.value)[0]>[] = [
	{
		type: "selection",
		fixed: "left",
		noExport: true,
	},
	{
		label: "序号",
		type: "index",
		fixed: "left",
		width: 80,
	},
	{
		label: "检查计划名称",
		formatter: (row) => row.name ?? "-",
	},
	{
		label: "检查类型",
		formatter: (row) =>
			getEnumOptionsField(CHECK_PLAN_TYPE_OPTIONS, "label", row.type) ?? "-",
	},
	{
		label: "检查部门",
		formatter: (row) => row.deptName ?? "-",
	},
	{
		label: "检查人员",
		formatter: (row) => row.checker ?? "-",
	},
	{
		label: "检查周期",
		formatter: (row) => `${row.checkStartDate}--${row.checkEndDate}` ?? "-",
	},
	{
		label: "计划检查企业数",
		formatter: (row) => row.enterpriseList?.length ?? "-",
	},
	{
		label: "操作",
		export: false,
		fixed: "right",
		width: "200",
		noExport: true,
		formatter(row) {
			return (
				<>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => detailDialogRef.value?.trigger("read", row)}
					>
						详情
					</el-button>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => detailDialogRef.value?.trigger("write", row)}
					>
						编辑
					</el-button>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => onDelete(row)}
					>
						删除
					</el-button>
				</>
			);
		},
	},
];
</script>

<template>
	<TableWidget
		ref="tableRef"
		v-loading="isLoading"
		:data="records"
		:columns="columns"
		h="100%!"
		@selection-change="(rows:any) => (selectedList = toRaw(rows))"
	/>
</template>
